package com.foreveross.proxyip.core.http;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;

import javax.net.SocketFactory;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.proxyip.core.pools.PoolsManager;
import com.foreveross.proxyip.entity.ProxyIpBean;

public abstract class ProxyIpHttpClientRequest implements HttpClientRequest {
//public  class ProxyIpHttpClientRequest {
	 /** The socket's SocketFactory. */
    protected static SocketFactory _socketFactory_ = null;
	
	protected static final Logger log =  LoggerFactory.getLogger(PoolsManager.class);
	public HttpClient getHttpClient(ProxyIpBean proxyIp,HttpParams httpParams){
		DefaultHttpClient httpclient = getHttpClient(httpParams);
	    HttpHost proxy = new HttpHost(proxyIp.getIp(), proxyIp.getPort());
	    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
	    return httpclient;
	}

	public DefaultHttpClient getHttpClient(HttpParams httpParams) {
		DefaultHttpClient httpclient=null;
		// 设置 user agent 
		String USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB6 (.NET CLR 3.5.30729)";
		if(httpParams==null){
			 httpParams = new BasicHttpParams();
		}
		HttpProtocolParams.setUserAgent(httpParams, USER_AGENT);
		httpParams.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
		///httpParams.setContentCharset("utf-8");
		httpclient = new DefaultHttpClient(httpParams);
		return httpclient;
	}
	
	
	/**
	 * ping ip
	 * 
	 * @param hostname
	 * @param port
	 * @return
	 * @throws SocketException
	 * @throws IOException
	 */
	protected boolean pingConnect(String hostname, int port,Integer connectTimeout)
			throws SocketException, IOException {
		if(!this.ping(hostname,connectTimeout)){
			return false;
		}
		Socket socket = null;
		try {
			InetAddress host = InetAddress.getByName(hostname);
			if (_socketFactory_ == null) {
				_socketFactory_ = SocketFactory.getDefault();
			}
			socket = _socketFactory_.createSocket();
			socket.connect(new InetSocketAddress(host, port), connectTimeout);
			return isConnected(socket);
		} finally {
			close(socket);
		}
		// / _connectAction_();
	}

	private void close(Socket socket) {
		if (socket != null) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Returns true if the client is currently connected to a server.
	 * <p>
	 * Delegates to {@link Socket#isConnected()}
	 * 
	 * @return True if the client is currently connected to a server, false
	 *         otherwise.
	 */
	private boolean isConnected(Socket socket) {
		if (socket == null) {
			return false;
		}
		return socket.isConnected();
	}
	
//	public static void main(String[] args) throws SocketException, IOException {
//		log.debug(new ProxyIpHttpClientRequest().ping("112.194.1.243"));
//		log.debug(new ProxyIpHttpClientRequest().pingConnect("112.194.1.243", 8088, 3000));
//		ProxyIpBean bean = new ProxyIpBean();
//		bean.setIp("112.194.1.243");
//		bean.setPort(8088);
//		HttpUriRequest request = new HttpGet("http://www.baidu.com/");
//		HttpResponse repon = new ProxyIpHttpClientRequest().getHttpClient(bean, null).execute(request );
//		HttpEntity entity = repon.getEntity();
//		System.out.print(EntityUtils.toString(entity));
//	}
	
	public boolean ping(String ipStr,int timeOut){
		 try {
			 if(StringUtils.isBlank(ipStr)){
				 return false;
			 }
			 String[] cells = StringUtils.split(ipStr,".");
			 byte[] ip = new byte[cells.length];
			 for(int i=0;i<cells.length;i++){
				 Integer cell = Integer.parseInt(cells[i]);
				 ip[i]= cell.byteValue();
			 }
			   InetAddress address = InetAddress.getByAddress(ip);
			   
//			   for (int i = 0; i < retry; i++) {
			    if (address.isReachable(2000)) {
			    	return true;
			    } else {
			    	return false;
			    }
//			   }
			  } catch (Exception e) {
			   e.printStackTrace();
			  }
			  return false;
	}
	
}
